#!/usr/bin/perl

use strict;
use lib qw(lib);
use CPANPLUS::Backend;
use CPANPLUS::Module;
use HTML::Template;

$CPANPLUS::Error::ERROR_FH = *STDOUT;

use CGI;
use CGI::Carp qw(fatalsToBrowser);

$| = 1;

my $cgi   = CGI->new();

print $cgi->header('text/html; charset=utf-8');

if (my $term = $cgi->param('term')) {
  my @found = sort { $a->{module} cmp $b->{module} } search($term);
  render({ search_results => \@found,
           term => $term,
           results => scalar @found,
           });
}
else {
  render();
}

sub render {
  my $args = shift;
  my $template = HTML::Template->new(
                  filename => "./content/search.html",
                  die_on_bad_params => 0);
  $template->param($args);
  print $template->output;
}

sub search { ;
  my $term = shift;
  my $cb  = CPANPLUS::Backend->new;
  # $cb->reload_indices(verbose => 1);

  my @found = $cb->search(type => 'module', allow => [qr/$term/]);
  return @found;
}

__END__

=head1 NAME

search.pl - performs searches for CPAN modules

=head1 FUNCTIONS

=over 4

=item render

Parses an HTML template and prints it to STDOUT. Takes one argument: 
a hash ref of variables to add as params to the template

=item search

Performs the search. Takes one argument: the search term. Returns an
array of hashrefs representing the modules found.

=back

=cut
